package com.fescoservice.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.directwebremoting.annotations.Param;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.spring.SpringCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.fescoservice.exception.FSException;
import com.fescoservice.model.BBS;
import com.fescoservice.model.BBSContent;
import com.fescoservice.model.Category;
import com.fescoservice.model.CategoryId;
import com.fescoservice.model.CategoryImage;
import com.fescoservice.model.CategoryImageId;
import com.fescoservice.service.CategoryService;
import com.fescoservice.service.ContentService;

@Controller
@RequestMapping("/action/Category.htm")
//@RemoteProxy(creator = SpringCreator.class, creatorParams = @Param(name = "beanName", value = "CategoryController"), name = "CategoryAjaxController")   

public class CategoryController {
	private static final Logger log = LogManager.getLogger(CategoryController.class);
		
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ContentService contentService;

	@RequestMapping(params = "cmd=list")
	public String listCategory(ModelMap map, HttpServletRequest request) throws FSException{
		String language = (String)request.getSession().getAttribute("userLanguage");
		log.debug("~~~~~~~~Controller begin listCategory~~~~~~~~"+language);
		getListModel(map,language);
		return "manage/categorylist";
	}
	
	@RequestMapping(params = "cmd=add")
	public String addCategory(CategoryId categoryId,ModelMap map ,HttpServletRequest request) throws FSException{
		//String boardCode1 =(String)request.getParameter("boardCode1");
		String boardCode2 =(String)request.getParameter("boardCode2");
		String boardCode3 =(String)request.getParameter("boardCode3");
		String code1Name =(String)request.getParameter("code1Name");
		String code2Name =(String)request.getParameter("code2Name");
		String code3Name =(String)request.getParameter("code3Name");
		String lang =(String)request.getSession().getAttribute("userLanguage");
		log.debug("~~~~~~~~Controller begin addCategory~~~~~~~~"+lang);
		boardCode2 = (null==boardCode2 || "".equals(boardCode2))?"FM0000":boardCode2;
		boardCode3 = (null==boardCode3 || "".equals(boardCode3))?"FB0000":boardCode3;
		//CategoryId categoryId = new CategoryId(boardCode1,boardCode2,boardCode3);	
		Category category = new Category(categoryId,code1Name,code2Name,code3Name,new Date(),new Date(),1L,lang,"0","N",1);	
	
		categoryService.saveCategory(category);
		getListModel(map,lang);
		return "manage/categorylist";
	}
	
	@RequestMapping(params = "cmd=update")
	public String updateCategory(CategoryId categoryId,ModelMap map,HttpServletRequest request) throws FSException{
		String lang =(String)request.getSession().getAttribute("userLanguage");
		String code1Name =(String)request.getParameter("code1Name");
		String code2Name =(String)request.getParameter("code2Name");
		String code3Name =(String)request.getParameter("code3Name");
		Category category = categoryService.findCategoryById(categoryId);
		log.debug("~~~~~~~~Controller updateCategory code1Name:　~~~~~~~~"+code1Name);
		if(!"FB0000".equals(categoryId.getBoardCode3()))
		{
			log.debug("~~~~~~~~Controller updateCategory~~~~~~~~"+code3Name);
			category.setCode3Name(code3Name);
		}else{
			if(!"FM0000".equals(categoryId.getBoardCode2()))
			{
				log.debug("~~~~~~~~Controller updateCategory~~~~~~~~"+code2Name);
				category.setCode2Name(code2Name);
			}else{
				log.debug("~~~~~~~~Controller updateCategory~~~~~~~~"+code1Name);
				category.setCode1Name(code1Name);
			}			
		}	
		category.setUpdateDate(new Date());
		categoryService.updateCategory(category);		
		getListModel(map,lang);
		return "manage/categorylist";
	}
	
	@RequestMapping(params = "cmd=delete")
	public String deleteCategory(CategoryId categoryId,ModelMap map,HttpServletRequest request) throws FSException{
		String lang =(String)request.getSession().getAttribute("userLanguage");
		log.debug("~~~~~~~~Controller deleteCategory begin~~~~~~~~"+categoryId.getBoardCode1());
		log.debug("~~~~~~~~Controller deleteCategory begin~~~~~~~~"+categoryId.getBoardCode2());
		log.debug("~~~~~~~~Controller deleteCategory begin~~~~~~~~"+categoryId.getBoardCode3());
		Category category = categoryService.findCategoryById(categoryId);	
		categoryService.deleteCategory(category);

		getListModel(map,lang);
		return "manage/categorylist";
	}
	
	@RequestMapping(params = "cmd=uploadImg")
	public String uploadCategoryImg(@RequestParam("imageFile") MultipartFile multipartFile,CategoryImageId categoryId,ModelMap map,HttpServletRequest request) throws FSException{
		String lang =(String)request.getSession().getAttribute("userLanguage");
		log.debug("~~~~~~~~Controller deleteCategory begin~~~~~~~~"+categoryId.getBoardCode1());
		log.debug("~~~~~~~~Controller deleteCategory begin~~~~~~~~"+categoryId.getBoardCode2());
		log.debug("~~~~~~~~Controller deleteCategory begin~~~~~~~~"+categoryId.getBoardCode3());

        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmssSS");String webUrl=request.getSession().getServletContext().getRealPath("/"); 
		File filePath = new File(webUrl+"uploadDir"+ File.separator + df1.format((new Date()).getTime()));   
        if (!filePath.exists()) {   
            filePath.mkdirs();   
        }   	
        String extName = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
		String fileName = filePath  + File.separator + "Image"+df2.format((new Date()).getTime())+extName;    
		File file = new File(fileName);   
		log.debug("~~~~~~~~Controller deleteCategory filePath : ~~~~~~~~"+fileName);
		try {   
			multipartFile.transferTo(file);  
			Long seq = categoryService.countCategoryImages(categoryId);
			categoryId.setImageSeq(++seq);
			CategoryImage image = new CategoryImage(categoryId,multipartFile.getOriginalFilename(),fileName,
					new Date(), new Date(),1L,lang,"N");				
			categoryService.saveCategoryImage(image);
		} catch (IllegalStateException e) {   
			e.printStackTrace();   
		} catch (IOException e) {   
			e.printStackTrace();   
		}   
		getListModel(map,lang);
		return "manage/categorylist";
	}
	
	@RequestMapping(params = "cmd=viewDetail")
	public String addDetail(CategoryId categoryId,ModelMap map,HttpServletRequest request) throws FSException{
		String lang =(String)request.getSession().getAttribute("userLanguage");
		List bbslist = contentService.findBBSByCategory(categoryId);
		BBS viewBBS = null;
		BBSContent viewBBSContent =null;
		List attachments = null;
		if(bbslist.size() > 0){
			viewBBS = (BBS)bbslist.get(0);
			viewBBSContent =contentService.findBBSContentById(viewBBS.getId());
			attachments =contentService.findBBSAttachesById(viewBBS.getId());
		}
	
		map.addAttribute("categoryId", categoryId);
		map.addAttribute("bbslist", bbslist);
		map.addAttribute("viewBBS", viewBBS);
		map.addAttribute("viewBBSContent", viewBBSContent);
		map.addAttribute("viewBBSAttaches", attachments);
		return "manage/bbspreview";
	}
	
	
	private ModelMap getListModel(ModelMap map, String language) throws FSException{	
		if(null==language || "".equals(language.trim())){
			throw new FSException("FS_ERROR_SESSIONOUT","");
		}
		List code1names  = categoryService.getCode1Names(language);
		List code2names  = new ArrayList();
		if(code1names.size()>0){
			String code1 = ((Category)code1names.get(0)).getId().getBoardCode1();	
			code2names  = categoryService.getCode2Names(language,code1);
		}
		Long counts  = categoryService.countCategories(language);
		List list = categoryService.getAllCategories(language);
		map.addAttribute("categorylist", list);
		map.addAttribute("code1names", code1names);
		map.addAttribute("code2names", code2names);
		map.addAttribute("counts", counts);
		return map;
	}
	
	//@RemoteMethod 
	public String getCode2Names(String language,String boardCode1) throws FSException{		
		List code2names  = categoryService.getCode2Names(language,boardCode1);
		log.debug("~~~~~~~~Ajax getCode2Names~~~~~~~~"+boardCode1);
		StringBuffer result=new StringBuffer("[");
		Category ctg =null;
		int index = 0;
		for(int i=0;i<code2names.size();i++){
			ctg=(Category)code2names.get(i);
			if(!"FM0000".equals(ctg.getId().getBoardCode2())){
				if(index++>0) result.append(",");				
				result.append("{'text':'").append(ctg.getCode2Name()).append("',");
				result.append("'value':'").append(ctg.getId().getBoardCode2()).append("'}");
			}
		}
		result.append("]");
		return result.toString();
	}
	
	//@RemoteMethod 
	public String checkCode1NameExist(String boardCode1) throws FSException{	
		log.debug("~~~~~~~~Ajax checkCode1NameExist~~~~~~~~"+boardCode1);
		Long count  = categoryService.countCode1Name(boardCode1);		
		String result="false";
		if(count>0){
			result="true";
		}
		return result;
	}

}
